/**
 * 
 */
var setting = {
	async: {
		enable: true,
		dataType: "json",
		url:"/HomeAcount/resource/loadResourceTree"
	},
	data: {
		simpleData: {
			enable: true,
			idKey : 'id',
			pIdKey : 'pId'
		}
	},
	callback: {
		onClick: zTreeOnClick
	}
};

$(function(){
	$.fn.zTree.init($("#resourceTree"), setting);
	//表单校验
	$('#resourceForm').validationEngine('attach', {
		autoHidePrompt: true,
		autoHideDelay : 3000,
		onValidationComplete : function(form, status) {
			if(status == true) {
				resourceSave();
			}
		}
	});
});

function zTreeOnClick(event, treeId, treeNode) {
//    var isParent = treeNod.isParent;
	var level = treeNode.level;
    if(level > 0) {
    	$.ajax({
			url : "/HomeAcount/resource/getResourceById",
			dataType : "json",
			type : "post",
			data : {
				id : treeNode.id
			},
			success : function(data) {
				if(data) {
					$('#opFlag').val("2");//修改
					if(data.type == 'menu') {
						$('#resource_type').empty()
							.append("<option value=''>---请选择---</tion>")
							.append("<option value='menu'>菜单</option>");
						$('#resourceForm').form('load', data);
						setFieldReadonly();
					}else {
						$('#resource_type').empty()
						.append("<option value=''>---请选择---</tion>")
						.append("<option value='button'>按钮</option>");
						$('#resourceForm').form('load', data);
						setFieldReadonly();
						releaseFieldReadonly("1");
					}
				}else {
					$(window.parent.alert("未加载到数据！"));
				}
			},
			error : function() {
				$(window.parent.alert("加载数据出错，请联系管理员！"));
			}
		});
    }
}

function setFieldReadonly() {
	$('#resource_type').attr('disabled','disabled');
	$('#resource_parentid').attr('disabled','disabled');
}

function releaseFieldReadonly(type) {
	$('#resource_parentid').removeAttr('disabled');
	if(type != '1') {
		$('#resource_type').removeAttr('disabled');
	}
}

function formRest() {
	$('#opFlag').val("1");//新增
	$('#resource_id').val('');
	releaseFieldReadonly('0')
	$('#resource_type').empty()
						.append("<option value=''>---请选择---</tion>")
						.append("<option value='button'>按钮</option>");
	$('#resourceForm').form('reset');
}

function resourceSave() {
	var data = $('#resourceForm').serializeJson();
	$.ajax({
		url : "/HomeAcount/resource/resourceSave",
		dataType : "json",
		type : "post",
		data : data,
		success : function(reData) {
			if(reData.flag) {
				$.fn.zTree.init($("#resourceTree"), setting);
				$('#opFlag').val('2');//将操作标志改为更新
				$(window.parent.alert("操作成功！"));
			}else {
				$(window.parent.alert("系统出错，请联系管理员！"));
			}
		},
		error : function() {
			$(window.parent.alert("系统出错，请联系管理员！"));
		}
	});
}


